/**
 * Created by cluo on 2017/12/20.
 */

import React, { Component } from 'react';
import {
    Platform,
    StyleSheet,
    Text,
    Button,
    MenuButton,
    Image,
    Alert,
    View,
    StatusBar,
    ScrollView,
    ListView,
    TouchableOpacity,
    TouchableWithoutFeedback,
    Dimensions
} from 'react-native';
import ViewPager from 'react-native-viewpager';
import Orientation from 'react-native-orientation';

import Common from './../Lib/Common';
import SubjectSub from './../Subject/sub';

const deviceW = Dimensions.get('window').width;
const BANNER_IMGS = [
    require('./../../images/banner/1.jpg'),
    require('./../../images/banner/2.jpg'),
    require('./../../images/banner/3.jpg')
];
var bannerImgs = [];
const len = 160;

export default class Home extends React.Component {
    static navigationOptions = {
        title: 'Home',
    };

    // 构造
    constructor(props) {
        super(props);

        var dataSource = new ViewPager.DataSource({
            pageHasChanged: (p1, p2) => p1 !== p2
        });
        //this._onBannerClick = this._onBannerClick.bind(this);
        this._onRecommendClick = this._onRecommendClick.bind(this);
        this._renderRow = this._renderRow.bind(this);
        var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        // 实际的DataSources存放在state中
        this.state = {
            dataSource: dataSource.cloneWithPages(BANNER_IMGS),
            listData: ds
        }
    }

    componentWillMount() {
        Orientation.lockToPortrait();
        Common.getBanners((result)=>{
            var dataSource = new ViewPager.DataSource({
                pageHasChanged: (p1, p2) => p1 !== p2
            });
            this.setState({
                dataSource: dataSource.cloneWithPages(result),
            })
        });

        Common.getTrainList((result)=>{
            var arr = result;
            var rows = [];
            var titles = ['男子初级训练项目', '男子中级训练项目', '男子高级级训练项目', '力量训练'];
            for (let i = 0; i < arr.length; i += 2) {
                var item = {id: i, title: '', left: null, right: null};
                item.left = (arr[i]);
                if (i < arr.length - 1) {
                    item.right = (arr[i + 1]);
                }
                item.title = titles[i/2];
                rows.push(item);
            }
            var ds = this.state.listData.cloneWithRows(rows);
            this.setState({listData: ds});
        });

    }

    _renderPage(data, pageID) {
        return (
            <TouchableWithoutFeedback
                style={styles.banner}
                onPress={() => this._onBannerClick(data, pageID)}>
                    <Image
                        source={{uri : Common.baseUrl + data.icon}}
                        style={styles.page} />
            </TouchableWithoutFeedback>
        );
    }

    _onBannerClick(data, pageID) {
        console.log('go subject:' + pageID);
        const { navigate } = this.props.navigation;
        navigate("SubjectSub", { id:data.id, title: data.name });
    }

    _onRecommendClick(data) {
        const { navigate } = this.props.navigation;
        navigate("List", { data: JSON.stringify(data), title: data.name });
    }

    _renderRow(rowData) {
        console.log(rowData.left.icon);
        console.log(rowData.right.icon);
        return (
            <View style={styles.row}>
                <Text style={styles.title}>{rowData.title}</Text>
                <View style={styles.content}>
                    <TouchableWithoutFeedback onPress={()=>{this._onRecommendClick(rowData.left)}}>
                        <View style={styles.item}>
                            <Image resizeMode={'stretch'} source={{uri:Common.baseUrl + rowData.left.icon}}
                                   style={styles.img}/>
                            <Text numberOfLines={2} style={styles.name}>{rowData.left.name}</Text>
                        </View>
                    </TouchableWithoutFeedback>
                    <TouchableWithoutFeedback onPress={()=>{this._onRecommendClick(rowData.right)}}>
                        <View style={styles.item}>
                            <Image resizeMode={'stretch'} source={{uri:Common.baseUrl + rowData.right.icon}}
                                   style={styles.img} />
                            <Text numberOfLines={2} style={styles.name}>{rowData.right.name}</Text>
                        </View>
                    </TouchableWithoutFeedback>
                </View>
            </View>
        );
    }

    render() {
        const { navigate } = this.props.navigation;
        return (
            <ListView
                style={styles.list}
                dataSource={this.state.listData}
                renderRow={this._renderRow}
                renderHeader={()=>{return(
                <View>
                    <StatusBar barStyle={'light-content'} />
                    <ViewPager
                        style={{height:130}}
                        dataSource={this.state.dataSource}
                        renderPage={this._renderPage.bind(this)}
                        isLoop={true}
                        autoPlay={true}/>

                </View>)}}>
            </ListView>

        );
    }
}

const styles = StyleSheet.create({
    banner: {
        flex: 1,
        width: deviceW,
        height: 210,
    },
    page: {
        flex: 1,
        height: 210,
        resizeMode: 'stretch'
    },
    row: {
        backgroundColor: 'white',
        marginTop: 15
    },
    title: {
        flexWrap: 'wrap',
        fontSize: 15,
        color: 'black',
        flex: 1,
        marginTop: 8,
        //marginBottom: 8,
        marginLeft: 8,
        height: 30,
    },
    content: {
        flexDirection:'row'
    },
    item: {
        flex:1,
        alignItems:'center'
    },
    img: {
        width:len,
        height:len
    },
    name: {
        width: len,
        flexWrap: 'wrap',
        fontSize: 12,
        color: 'black',
        flex: 1,
        marginTop: 8,
        height: 30,
        textAlign: 'center'
    },
    list: {
        flex:1,
        backgroundColor:'#ECEFF2'
    }
});
